import 'package:flutter/material.dart';
import '../../core/base/base_view_model.dart';
import '../../core/http/http_client.dart';
import 'product_model.dart';

class ProductListViewModel extends BaseViewModel {
  final _httpClient = HttpClient();
  List<ProductModel> products = [];
  List<ProductModel> filteredProducts = [];
  String searchKeyword = '';
  int currentPage = 1;
  int pageSize = 10;
  int total = 0;
  bool hasMore = true;

  Future<void> fetchProducts({bool refresh = true}) async {
    try {
      if (refresh) {
        currentPage = 1;
        products.clear();
        hasMore = true;
      }
      if (!hasMore) return;

      setBusy(true);
      final response = await _httpClient.get('/product/list', params: {
        'page': currentPage,
        'page_size': pageSize,
      });
      
      if (response.code == 200) {
        final responseData = response.data['data'];
        final list = responseData['list'] as List;
        total = responseData['total'] as int;
        
        final newProducts = list.map((json) {
          try {
            return ProductModel.fromJson(json);
          } catch (e) {
            print('Error parsing product: $json\nError: $e');
            throw e;
          }
        }).toList();
        
        products.addAll(newProducts);
        hasMore = products.length < total;
        if (hasMore) currentPage++;
        
        _filterProducts();
        notifyListeners();
      } else {
        setError('获取商品列表失败');
      }
    } catch (e) {
      setError('获取商品列表失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  Future<void> deleteProduct(int id) async {
    try {
      setBusy(true);
      final response = await _httpClient.delete('/product/$id');
      
      if (response.code == 200) {
        products.removeWhere((product) => product.id == id);
        _filterProducts();
        notifyListeners();
      } else {
        setError('删除商品失败');
      }
    } catch (e) {
      setError('删除商品失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  Future<void> createProduct(Map<String, dynamic> productData) async {
    try {
      setBusy(true);
      final response = await _httpClient.post('/product', data: productData);
      
      if (response.code == 201) {
        await fetchProducts();
      } else {
        setError('创建商品失败');
      }
    } catch (e) {
      setError('创建商品失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  Future<void> updateProduct(int id, Map<String, dynamic> productData) async {
    try {
      setBusy(true);
      final response = await _httpClient.put('/product/$id', data: productData);
      
      if (response.code == 200) {
        await fetchProducts();
      } else {
        setError('更新商品失败');
      }
    } catch (e) {
      setError('更新商品失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  void searchProducts(String keyword) {
    searchKeyword = keyword;
    _filterProducts();
    notifyListeners();
  }

  void _filterProducts() {
    if (searchKeyword.isEmpty) {
      filteredProducts = List.from(products);
    } else {
      filteredProducts = products.where((product) =>
        product.name.toLowerCase().contains(searchKeyword.toLowerCase()) ||
        product.description.toLowerCase().contains(searchKeyword.toLowerCase())
      ).toList();
    }
  }
}